import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hive_flutter/hive_flutter.dart';

class ChatHistoryPage extends StatelessWidget {
  const ChatHistoryPage({super.key});

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;
    final Box box = Hive.box('app');
    final List<String> sessionIds = _loadAllSessionIds(box);

    return Scaffold(
      appBar: AppBar(title: const Text('历史记录')),
      body:
          sessionIds.isEmpty
              ? Center(
                child: Text(
                  '暂无历史会话',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              )
              : ListView.separated(
                itemCount: sessionIds.length,
                separatorBuilder:
                    (_, __) =>
                        Divider(height: 1, color: cs.outline.withOpacity(0.15)),
                itemBuilder: (context, index) {
                  final String id = sessionIds[index];
                  final String key = 'aiChatMessages_' + id;
                  final List<dynamic>? msgs = box.get(key) as List<dynamic>?;
                  final int count = msgs?.length ?? 0;
                  final String preview = _buildPreview(msgs);
                  final String timeText = _buildTimeText(msgs);
                  return ListTile(
                    leading: const Icon(Icons.forum_outlined),
                    title: Text(
                      '会话 $id',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    subtitle: Text(
                      '$preview\n$count 条消息 · $timeText',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    isThreeLine: true,
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => context.push('/ai/history/$id'),
                  );
                },
              ),
    );
  }

  List<String> _loadAllSessionIds(Box box) {
    final List<String> ids = [];
    try {
      final List<dynamic>? saved = box.get('aiSessionIds') as List<dynamic>?;
      if (saved != null) {
        for (final s in saved) {
          final str = s?.toString();
          if (str != null && str.isNotEmpty && !ids.contains(str)) ids.add(str);
        }
      }
      final String? cur = box.get('aiConversationId') as String?;
      if (cur != null && cur.isNotEmpty && !ids.contains(cur))
        ids.insert(0, cur);
    } catch (_) {}
    return ids;
  }

  String _buildPreview(List<dynamic>? msgs) {
    if (msgs == null || msgs.isEmpty) return '——';
    for (int i = msgs.length - 1; i >= 0; i--) {
      final m = msgs[i];
      if (m is Map) {
        final String text = (m['text'] ?? '').toString();
        if (text.isNotEmpty) return text;
      }
    }
    return '——';
  }

  String _buildTimeText(List<dynamic>? msgs) {
    if (msgs == null || msgs.isEmpty) return '无时间';
    final m = msgs.last;
    if (m is Map) {
      final int ts = int.tryParse((m['ts'] ?? '0').toString()) ?? 0;
      if (ts > 0) {
        final dt = DateTime.fromMillisecondsSinceEpoch(ts);
        return '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
      }
    }
    return '无时间';
  }
}
